package com.zznj.xzjc;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogDownload;
import com.zznj.xzjc.activity.FileDisplayActivity;
import com.zznj.xzjc.activity.NetPicShowActivity;
import com.zznj.xzjc.adapter.index.DictionaryAdapter;
import com.zznj.xzjc.adapter.index.StepAdapter;
import com.zznj.xzjc.base.BaseActivity;
import com.zznj.xzjc.bean.index.DictionaryData;
import com.zznj.xzjc.bean.index.StepData;
import com.zznj.xzjc.net.SharedHelper;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.net.entity.LoginBean;
import com.zznj.xzjc.net.rxjava.HttpMethods;
import com.zznj.xzjc.net.subscribers.ProgressSubscriber;
import com.zznj.xzjc.net.subscribers.SubscriberOnNextListener;
import com.zznj.xzjc.utils.FileUtils;
import com.zznj.xzjc.utils.StringUtils;
import com.zznj.xzjc.utils.fileutils.OkManager;
import com.zznj.xzjc.view.MaxHeightRecyclerView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.FormBody;


/**
 * Created by JY on 2017/11/15.
 */

public class ActivityAnJianDetail extends BaseActivity {

    @BindView(R.id.content)
    WebView webView;
    @BindView(R.id.rightInfo)
    TextView rightInfo;
    @BindView(R.id.righImage)
    ImageView righImage;
    @BindView(R.id.xzhjTv)
    TextView xzhjTv;

    @BindView(R.id.dicList)
    MaxHeightRecyclerView dicList;
    @BindView(R.id.zheCeng)
    View zheCeng;



    @Override
    protected int getLayoutId() {
        return R.layout.gyss_index_web_layout;
    }

    private String id;
    private LoginBean user;
    private String contentTitle;
    private String collectType;
    private String infoSign;
    private String fromActivity;
    private String caseId;
    private String caseState;
    @Override
    public void initView() {
        user = new Gson().fromJson(SharedHelper.readValueByKeyForString(mContext, "Member"), LoginBean.class);
        caseId = getIntent().getExtras().getString("caseId");


        WebSettings wvSetting = webView.getSettings();
        wvSetting.setJavaScriptEnabled(true);
        wvSetting.setAllowFileAccess(true);
        wvSetting.setBuiltInZoomControls(false);
        wvSetting.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new TestJavaScriptInterface(),"app");
        setTitle("案件详情");

        initDictionary();
    }

    private class TestJavaScriptInterface{

        @JavascriptInterface
        public void downloadCaseFile(String downUrl,String fileName){
            Log.i("xxxxx",fileName);
            if (FileUtils.getIcon(fileName) == R.mipmap.icon_file_pic) {
                //打开图片
                List<String> pList = new ArrayList<>();
                pList.add(HttpMethods.BASE_URL+downUrl);
                Bundle bundle = new Bundle();
                bundle.putInt("item", 0);
                bundle.putSerializable("listPath", (Serializable) pList);
                RxActivityTool.skipActivity(mContext, NetPicShowActivity.class, bundle);
            }else{
                //下载文件
                downFile(HttpMethods.BASE_URL+downUrl,fileName);
            }
        }
    }


    private StepAdapter dicAdapter;
    private int selectPosition;
    private List<StepData> dlist;
    private void initDictionary() {
        dlist = new ArrayList<>();
        ((SimpleItemAnimator) dicList.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        dicList.setLayoutManager(linearLayoutManager);
        dicAdapter = new StepAdapter(R.layout.gyss_item_select_step, dlist);
        dicList.setAdapter(dicAdapter);
        dicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selectPosition = position;
                zheCeng.setVisibility(View.GONE);
                dicList.setVisibility(View.GONE);
                xzhjTv.setText(dlist.get(position).getStepName());
                stepId = dlist.get(position).getStepId();
                caseState = dlist.get(position).getCaseState();
                taskInstId = StringUtils.toString(dlist.get(position).getTaskInstId());
                Log.i("requestUrl：", HttpMethods.BASE_URL+"xzapi/caseQuery/detail?userId="+user.getUserId()+"&caseId="+caseId+"&stepId="+stepId+"&taskInstId="+taskInstId+"&caseState="+caseState);
                webView.loadUrl(HttpMethods.BASE_URL+"xzapi/caseQuery/detail?userId="+user.getUserId()+"&caseId="+caseId+"&stepId="+stepId+"&taskInstId="+taskInstId+"&caseState="+caseState);
            }
        });
    }


    private RxDialogDownload downDialog;
    private void initDownLoadDialog() {
        downDialog = new RxDialogDownload(this);
        downDialog.setCanceledOnTouchOutside(false);
        downDialog.getTextView().setText("下载中...");
        downDialog.show();
    }

    private void downFile(String downUrl,String fileName){
        File pFile = new File(FileUtils.getRootFile(),fileName);
        if (!pFile.exists()) {
            initDownLoadDialog();
            OkManager.getInstance().downLoadFile(downUrl, fileName, new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    downDialog.dismiss();
                    if(msg.what == 100){
                        RxToast.normal("下载成功！");
                        Bundle bundle = new Bundle();
                        bundle.putString("fileName",fileName);
                        RxActivityTool.skipActivity(activity, FileDisplayActivity.class,bundle);
                    }else if(msg.what == -1){
                        RxToast.normal("下载失败！");
                        pFile.delete();
                    }
                    super.handleMessage(msg);
                }
            });
        }else{
            Bundle bundle = new Bundle();
            bundle.putString("fileName",fileName);
            RxActivityTool.skipActivity(activity, FileDisplayActivity.class,bundle);
        }
    }

    private boolean isShouCang = false;
    private void isCollect() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                String data = baseBean.getMessage();
                if ("false".equals(data)) {
                    isShouCang = false;
                    righImage.setImageResource(R.mipmap.gyss_sc_wsc_white_img);
                    rightInfo.setText("收藏");
                } else {
                    isShouCang = true;
                    righImage.setImageResource(R.mipmap.gyss_sc_ysc_white_img);
                    rightInfo.setText("已收藏");
                }
            }
        };
        FormBody requestBody = new FormBody.Builder()
                .add("infoId", id)
                .add("userId", user.getUserId())
                .build();
        HttpMethods.getInstance().isCollection(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @OnClick({R.id.zjsjyqLinear})
    public void onViewClick(View v){
        if(v.getId() == R.id.zjsjyqLinear){
            if(isShouCang){
                canCelShouCang();
            }
        }
    }

    private void canCelShouCang(){
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                isShouCang = false;
                righImage.setImageResource(R.mipmap.gyss_sc_wsc_white_img);
                rightInfo.setText("收藏");
                RxToast.normal("取消成功！");
            }
        };
        FormBody requestBody = new FormBody.Builder()
                .add("infoId", id)
                .add("userId", user.getUserId())
                .build();
        HttpMethods.getInstance().cancelCollect(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private String stepId="";
    private String taskInstId = "";
    private void getStepInfo(){
        SubscriberOnNextListener<BaseBean<List<StepData>>> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                dlist.addAll(baseBean.getResult());
                dicAdapter.notifyDataSetChanged();
                selectPosition = 0;
                dicAdapter.setSelectPosition(selectPosition);
                stepId = baseBean.getResult().get(0).getStepId();
                caseState = baseBean.getResult().get(0).getCaseState();
                taskInstId = StringUtils.toString(baseBean.getResult().get(0).getTaskInstId());
                webView.loadUrl(HttpMethods.BASE_URL+"xzapi/caseQuery/detail?userId="+user.getUserId()+"&caseId="+caseId+"&stepId="+stepId+"&taskInstId="+taskInstId+"&caseState="+caseState);
            }
        };
        FormBody requestBody = new FormBody.Builder()
                .add("caseId", caseId)
                .build();
        HttpMethods.getInstance().queryCaseStep(new ProgressSubscriber<>(onNextListener, mContext, true), caseId);
    }

    @Override
    public void initData() {
        getStepInfo();
    }

    @OnClick({R.id.xzhjTv,R.id.zheCeng})
    public void onClick(View view){
        if(view.getId() == R.id.xzhjTv){
            if(zheCeng.getVisibility() == View.VISIBLE){
                zheCeng.setVisibility(View.GONE);
                dicList.setVisibility(View.GONE);
            }else{
                zheCeng.setVisibility(View.VISIBLE);
                dicList.setVisibility(View.VISIBLE);
                dicAdapter.setSelectPosition(selectPosition);
            }
        }else if(view.getId()==R.id.zheCeng){
            zheCeng.setVisibility(View.GONE);
            dicList.setVisibility(View.GONE);
        }
    }
}

